package com.happypets.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.happypets.model.PetBean;
import com.happypets.servicesImpl.PetServiceImpl;

/**
 * Servlet implementation class KeyWordsSearch
 */
public class KeyWordsSearch extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public KeyWordsSearch() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//用于关键词搜索
		
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json;charset=UTF-8");
		response.setHeader("Cache-Control", "no-store"); 
		
		PetServiceImpl psi = new PetServiceImpl();
		
		PrintWriter out = response.getWriter();
		
		
		
		String showNum = request.getParameter("showNumber");
		String keyWord = request.getParameter("keyWord");
		
		if( null != request.getParameter("flag")){
			List<Map<String, String>> lm = null;
			//查询页数
			lm = new ArrayList<Map<String,String>>();
			Map<String,String> mp = new HashMap<String,String>();
			
			mp.put("pages", ""+psi.searchPetCount(keyWord));
			lm.add(mp);
			
			Gson gson=new Gson();
			String json=gson.toJson(lm);
			System.out.println("deal ----\n"+json);
			out.write(json);
			
			out.flush();
			out.close();
			
		}else{
			List<PetBean> lm = null;
			//查询结果
			String cNumber = request.getParameter("pageNumber");
			if(cNumber != null && showNum != null){
				lm = psi.searchPageResult(Integer.parseInt(showNum), Integer.parseInt(cNumber), keyWord);
			}
			
			Gson gson=new Gson();
			String json=gson.toJson(lm);
			System.out.println("deal ----\n"+json);
			out.write(json);
			
			out.flush();
			out.close();
			
			
		}

		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
